package com.sky.controller.common;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author majun
 * @package com.sky.controller.common
 * @date 2024/12/7 14:12
 */

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * AliOss文件上传
     *
     * @param file 文件upload
     * @return 文件链接
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {

        log.info("文件上传 : {}", file);

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //获取原始文件名后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            String url = aliOssUtil.upload(file.getBytes(), objectName);

            return Result.success(url);

        } catch (IOException e) {
            log.error("文件上传失败");
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);

    }

}
